//
//  NoteEditViewVc-DragDrop.swift
//  xiaofenshu
//
//  Created by zhu jinlong on 2021/5/21.
//

import Foundation

extension NoteEditViewVc:UICollectionViewDragDelegate {
    func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
        let photo = self.phones[indexPath.item]
        let dragItem =  UIDragItem(itemProvider: NSItemProvider(object: photo));
        dragItem.localObject = photo
        return [dragItem]
    }
}

extension NoteEditViewVc:UICollectionViewDropDelegate {
    func collectionView(_ collectionView: UICollectionView, dropSessionDidUpdate session: UIDropSession, withDestinationIndexPath destinationIndexPath: IndexPath?) -> UICollectionViewDropProposal {
        if phoneCollectionView.hasActiveDrag{
            return UICollectionViewDropProposal.init(operation: UIDropOperation.move, intent: .insertAtDestinationIndexPath)
        }
        
        return UICollectionViewDropProposal.init(operation: .forbidden)
    }
    
    func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
        if coordinator.proposal.operation == .move,
           let item = coordinator.items.first,
           let sourceIndexPath = item.sourceIndexPath,
           let destinationIndexPath = coordinator.destinationIndexPath{
            collectionView.performBatchUpdates {
                phones.remove(at: sourceIndexPath.item)
                phones.insert(item.dragItem.localObject as! UIImage, at: destinationIndexPath.item)
                collectionView.moveItem(at: sourceIndexPath, to: destinationIndexPath)
            }
            coordinator.drop(item.dragItem, toItemAt: destinationIndexPath)
            
        }
    }
    
    
}
